"""
file: test_api.py
Author: 城下秋草
Date: 2024/12/11
Desc: 接口测试
"""
from time import sleep

from playwright.sync_api import sync_playwright, Route, expect

playwright = sync_playwright().start()
api_context = playwright.request.new_context(base_url='https://dummyjson.com')

response = api_context.get('users/1')
assert response.ok
print(response.status_text)
print(response.status)
print(response.json())

new_user ={
    'firstName':'城下秋草',
    'lastName':'黄',
    'age':30
}
res = api_context.post(url='/users/add',
                 data=new_user,
                 headers={'content-type':'application/json'})
print(res.status_text, res.status)
print(res.text())


browser = playwright.chromium.launch(
    headless=False,
    slow_mo=500,
    args=['--window-position=1024,-850']
)

context=browser.new_context()
page = context.new_page()

def handle(route: Route):
    response = route.fetch()
    json = response.json()
    json.append({'name':'小苹果', 'id': 100})
    route.fulfill(json=json)

# page.route(
#     url='https://demo.playwright.dev/api-mocking/api/v1/fruits',
#     handler=handle
# )

page.route_from_har(
    har='./har/test.har',
    url='https://demo.playwright.dev/api-mocking/api/v1/fruits',
    update=False
)

page.goto('https://demo.playwright.dev/api-mocking/')
expect(page.get_by_text('小苹果')).to_be_visible()
sleep(3)

context.close()
browser.close()
playwright.stop()